/*
 * prn_func.c
 *
 *  Created on: 27.11.2011
 *      Author: alexs
 */
#include "prn_func.h"
#include "stm32f10x_conf.h"

size_t ulong2str(char * c, const size_t len, const uint32_t a) {
	char tmpc[11]={0,0,0,0,0,0,0,0,0,0,0};
	int i;
	uint32_t tmp=a;

	for (i=0;i<10;i++) {
		tmpc[9-i]=(tmp %10)+'0';
		tmp/=10;
	}
	i=0;
	while ((tmpc[i]=='0')&&(i<9)) i++;
	if (strlen(&tmpc[i])<len) {
		strncpy(c,&tmpc[i],len);
		return strlen(&tmpc[i]);
	} else {return 0;}

}

size_t ulong2hstr(char * c, const size_t len, const uint32_t a) {
	char tmpc[9]={0,0,0,0,0,0,0,0,0};
	int i;
	uint32_t tmp=a;

	for (i=0;i<8;i++) {
		tmpc[7-i]=(tmp&0x0000000f);
		if (tmpc[7-i]>9) tmpc[7-i]+='A'-10; else tmpc[7-i]+='0';
		tmp>>=4;
	}
	i=0;
	//	while ((tmpc[i]=='0')&&(i<7)) i++;
	if (strlen(&tmpc[i])<len) {
		strncpy(c,&tmpc[i],len);
		return strlen(&tmpc[i]);
	} else {return 0;}
}

void DBG(const dbg_info_type inft, const char * p1, const uint32_t p2, const char * p3) {
	int tmp;

	while (DMA_GetCurrDataCounter(USART2TXDMA));
	DMA_Cmd(USART2TXDMA,DISABLE);
	strncpy(USART_TX_BUFF,p1,USART_TX_BUFF_SIZE);
	tmp=strlen(USART_TX_BUFF);
	if (inft!=STR) {
	if (inft==HEX) {ulong2hstr(&USART_TX_BUFF[tmp],USART_TX_BUFF_SIZE-tmp,(uint32_t)p2);}
	else {ulong2str(&USART_TX_BUFF[tmp],USART_TX_BUFF_SIZE-tmp,(uint32_t)p2);}
 	tmp=strlen(USART_TX_BUFF);
	strncpy(&USART_TX_BUFF[tmp],p3,USART_TX_BUFF_SIZE-tmp);
	tmp=strlen(USART_TX_BUFF);
	}
	DMA_SetCurrDataCounter(USART2TXDMA,tmp);
	DMA_Cmd(USART2TXDMA,ENABLE);
}
